import assign from 'object-assign';
import blacklist from 'blacklist';
import React from 'react';
import ReactDOM from 'react-dom';
import {info} from '../toast';
import {FieldContainer, FieldBox} from '../form'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'

import { createDocument } from '../../actions/onboarding.hr.action'
import { fileUpload } from '../../actions/file.action'
import { updateAvatar } from '../../actions/app.action'


if (typeof document !== 'undefined') {
  var MediumEditor = require('medium-editor');
}
import 'medium-editor/dist/css/medium-editor.css'
import 'medium-editor/dist/css/themes/default.css'
import './style.basic'

const MAX_SIZE_IMAGE = 20971520;

@connect(({}) => ({}), dispatch => ({ actions: bindActionCreators({ createDocument, fileUpload, updateAvatar }, dispatch) }))
class Editor extends React.Component {
  static defaultProps = {
    tag: 'div'
  };

  constructor(props) {
    super(props);

    this.state = {
      text: this.props.text,
      error: false,
      active: false
    };
  }

  componentDidMount() {
    const dom = ReactDOM.findDOMNode(this.refs.medium);
    const options={
      placeholder: {
        text: this.props.placeholder || ''
      },
      toolbar: {
        relativeContainer: this.refs.toolbar,
        updateOnEmptySelection: true,
        static: true,
        sticky: true, 
        buttons: this.props.buttons || ['bold', 'italic', 'underline','anchor','h2', 'h3','quote',]
      }
    };
    this.medium = new MediumEditor(dom, options);
    this.medium.subscribe('editableInput', (e) => {
      this._updated = true;
      this.change(dom.innerHTML);
    });
    if(!!this.props.hasImage){
      const img = document.createElement("li");
      img.innerHTML = '<button class="medium-editor-action" title="image" ><b>img</b></button>';
      img.classList.add('toolbar-item-img'); 
      img.addEventListener('click',::this.addImg);
      this.refs.toolbar.querySelector('.medium-editor-toolbar-actions').appendChild(img);
    }


    var p = this.medium.elements[0]
    var s = window.getSelection(),
      r = document.createRange();
      r.setStart(p, 0);
      r.setEnd(p, 0);
      s.removeAllRanges();
      s.addRange(r);
  }

  addImg() {
    var node = this.medium.options.contentWindow.getSelection().anchorNode;
    if(node) {
      this.refs.file.click();
      //this.medium.options.ownerDocument.execCommand('insertImage', false, 'http://img.blog.csdn.net/20160510144849061');
    }
  }

  handleFileChange(e) {
    e.preventDefault();
    e.stopPropagation();
    info('上传图片中', true);
    const files = this.refs.file.files
    const maxSize = this.props.fileSize || MAX_SIZE_IMAGE/1024;
    const sizeText = (maxSize/1024).toFixed(2);
    function next(i) {
      const file = files[i]
      if (!file) {
        // clear
        this.refs.file.value = ''
        return
      }
      if (this.props.accept === 'image/*') {
        if (file.type.indexOf('image') !== 0) {
          this.refs.file.value = ''
          alert('只能上传图片!')
          return
        }

      }
      if (file.size > maxSize*1024) {
        this.refs.file.value = ''
        alert(`图片最大不能超过${sizeText}MB!`)
        return
      }
      const reader = new FileReader()
      reader.onload = e => this.handleFileLoaded(e, file)
      reader.readAsDataURL(file);
      next.call(this, i+1)
    }

    next.call(this, 0)
  }

  handleFileLoaded(e, _file) {

    const dataURL = e.target.result;
    const mimeType = _file.type || dataURL.split(",")[0].split(":")[1].split(";")[0];

    const file = {
      // 文件大小
      size: e.total,
      // 文件类型
      type: mimeType,
      name: _file.name,
      file: _file,
      dataURL
    }
    this.props.actions.updateAvatar({
      x: 0,
      y: 0,
      e: 0
    }, ({ presignedPutUrl, publicGetUrl }) => {
      this.props.actions.fileUpload({
        url: presignedPutUrl,
        file: file.file,
        cb: () => {
          info();
          this.medium.options.ownerDocument.execCommand('insertImage', false, publicGetUrl);
        }
      })
    })
    /*
    this.props.actions.createDocument({ scenario: 2, documentName: file.name, storageStatus: 1 }, data => {
      const { documentId, presignedUrl } = data
      this.props.actions.fileUpload({
        file: file.file,
        url: presignedUrl,
        cb: () => {
          console.log(arguments);
          this.medium.options.ownerDocument.execCommand('insertImage', false, presignedUrl);
          info();
        }
      })
    })
    */

  }


  componentDidUpdate() {
    this.medium.restoreSelection();
  }

  componentWillUnmount() {
    this.medium.destroy();
  }

  componentWillReceiveProps(nextProps) {
    if (nextProps.text !== this.state.text && !this._updated) {
      this.setState({ text: nextProps.text });
    }

    if (this._updated) this._updated = false;
  }
  handleBlur(e) {
    setTimeout(()=>{
      this.setState({
        active: false,
      })
    }, 0);
  }
  handleFocus(e) {
    this.setState({
      active: true,
    })
  }
  render() {
    const tag = this.props.tag;

    const { label, name, required, className, children, bubbleList, width,...others } = this.props
    const props = blacklist(others, 'tag', 'contentEditable', 'dangerouslySetInnerHTML');

    assign(props, {
      dangerouslySetInnerHTML: { __html: this.state.text },
      ref: 'medium',
      key: 'medium',
      className: '',
      onFocus: ::this.handleFocus,
      onBlur: ::this.handleBlur,
    });

    if (this.medium) {
      this.medium.saveSelection();
    }
    const MediumEditor = React.createElement(tag, props);

    return (
      <FieldBox
        label={label}
        name={name}
        required={required}
      >
        <FieldContainer
          hasBox={true}
          active={this.state.active}
          error={this.state.error}
          msg={this.state.msg}
          className={className}
          bubbleList={bubbleList}
          width={width}
        >
          <div data-role="editor" {...(this.props)} className={this.state.active ? '' : 'editor-blur'} >
            <div className={'toolbar'} ref={'toolbar'}></div>
            {MediumEditor}
            <input 
              accept={'image/*'}
              type="file" 
              ref="file"
              onChange={::this.handleFileChange}
              style={{display: 'none'}}
            />
          </div>
        </FieldContainer>
      </FieldBox>
    );
    //return React.createElement(tag, props);
  }

  change(text) {
    if (this.props.onChange) this.props.onChange(text, this.medium);
  }
  /*constructor(props) {
    super(props);
    this.displayName = 'Editor';
  }
  componentDidMount() {
    const medium = this.refs.mediumEditor.medium;
    const toolbar = this.refs.toolbar;
    const opts = {
      toolbar: {
        stickyTopOffset: 50,
        sticky: true, 
        static: true,
        align: 'center',
        updateOnEmptySelection: true,
      }
    }
    medium.init(ReactDOM.findDOMNode(this.refs.mediumEditor), opts);
  }
  render() {
    console.log();
    return (
      <div data-role="editor">
        <div className={'toolbar'} ref={'toolbar'}></div>
        <MediumEditor
          text={this.props.text}
          ref={'mediumEditor'}
          options={{
            placeholder: {
              text: this.props.placeholder,
            },
            
            toolbar: {
              stickyTopOffset: 50,
              sticky: true, 
              static: true,
              align: 'center',
              updateOnEmptySelection: true,
            }
          }} 
          onChange={value => {
            this.props.onChange && this.props.onChange(value);
          }}
        />
      </div>
    );
  }*/
}

export default Editor;
